import { publishJobadFill } from "./bg-messagelistener"
import { getFromStorage } from './utils'
import channelJsData1 from "./channel-js/channel-1.js"
import publishadinfo1 from "./publishadinfo/info-1.js"

import channelJsData2 from "./channel-js/channel-2.js"
import publishadinfo2 from "./publishadinfo/info-2.js"

import channelJsData3 from "./channel-js/channel-3.js"
import publishadinfo3 from "./publishadinfo/info-3.js"

import channelJsData4 from "./channel-js/channel-4.js"
import publishadinfo4 from "./publishadinfo/info-4.js"

const publishadinfos = [
  publishadinfo1,
  publishadinfo2,
  publishadinfo3,
  publishadinfo4,
]
const channelJsDatas = [
  channelJsData1,
  channelJsData2,
  channelJsData3,
  channelJsData4,
]


chrome.runtime.getStorageLocalPromise = keys => new Promise((resolve, reject) => {
  chrome.storage.local.get(keys, (data) => {
    if (chrome.runtime.lastError) {
      return reject(chrome.runtime.lastError)
    }
    resolve(data)
  })
})
chrome.runtime.setStorageLocalPromise = obj => new Promise((reject, resolve) => {
  chrome.storage.local.set(obj, () => {
    if (chrome.runtime.lastError) return reject(chrome.runtime.lastError)
    resolve(true)
  })
})
chrome.runtime.removeStorageLocalPromise = keys => new Promise((resolve, reject) => {
  chrome.storage.local.remove(keys, () => {
    if (chrome.runtime.lastError) return reject(chrome.runtime.lastError)
    resolve(true)
  })
})



chrome.runtime.onInstalled.addListener((installedDetails) => {
  // emit in every reload
  if (installedDetails.reason === "update") {
    console.log("chrome extension update success")
  }
})

if (!chrome.tabs.onUpdated.hasListener(onUpdatedListener)) {
  chrome.tabs.onUpdated.addListener(onUpdatedListener)
}
// eslint-disable-next-line no-unused-vars
function onUpdatedListener(tabId, changeInfo, tab) {
  // read changeInfo data and do something with it
  // like send the new url to contentscripts.js
  if (changeInfo.url) {
    chrome.tabs.sendMessage(tabId, {
      message: "PAGE_URL_CHANGED",
      url: changeInfo.url,
    })
  }
}

const webRequestMap = new Map()
const windowsFilledState = new Map()

// 监听消息，当收到消息时，回调函数被触发
if (!chrome.runtime.onMessage.hasListener(messageListener)) {
  // 添加消息监听器
  chrome.runtime.onMessage.addListener(messageListener)
}
function messageListener(request, sender, sendResponse) {
  if (request.target && request.job) {
    console.log(
      "backgrond.js chrome.runtime.onMessage request.target: >>",
      request.target
    )
    console.log(
      "backgrond.js chrome.runtime.onMessage request.job: >>",
      request.job
    )
    // step1: 获取目标页面的配置和即将发送过去的表单数据

    // step2: 打开新窗口, 并发送表单数据，并建立和sender一对一的对应关系
    chrome.windows.get(
      sender.tab.windowId,
      { populate: true },
      function (currentWindow) {
        const width = parseInt(currentWindow.width * 0.8) // 新窗口的宽度
        const height = parseInt(currentWindow.height * 0.8) // 新窗口的高度

        // 计算新窗口的左上角坐标
        const left = Math.round(
          currentWindow.left + currentWindow.width / 2 - width / 2
        )
        const top = Math.round(
          currentWindow.top + currentWindow.height / 2 - height / 2
        )

        chrome.windows.create(
          {
            url: request.targetUrl,
            type: "popup",
            width,
            height,
            left,
            top,
          },
          function (newWindow) {
            console.log("打开目标页面成功 newWindow", newWindow)
            sendResponse("====打开目标页面成功====")
            chrome.tabs.onUpdated.addListener(function listener(
              tabId,
              changeInfo
            ) {
              if(windowsFilledState.get(tabId)){
                // 已经填充过了，不要重复触发了
                return
              }
              // 为新页面注入填充脚本以自动填充
              if (
                tabId === newWindow.tabs[0].id &&
                changeInfo.status === "complete"
              ) {
                try {
                  const obj = JSON.parse(publishadinfos[request.target - 1])
                  const channelJsData = channelJsDatas[request.target - 1]
                  const job = request.job
                  const beisen_constant = JSON.parse(
                    obj.adDetail.beisen_constant
                  )

                  const DEGREE_MAP = {
                    小学: "初中及以下",
                    初中及以下: "初中及以下",
                    高中: "高中",
                    "中专/中技": "中专/中技",
                    大专: "大专",
                    本科: "本科",
                    硕士: "硕士",
                    硕士研究生: "硕士",
                    MBA: "硕士",
                    博士: "博士",
                    大专及以上: "大专",
                    本科及以上: "本科",
                    不限: "不限",
                  }

                  const EXP_MAP = {
                    "1年以下": "1年以内",
                    "1-3年": "1-3年",
                    "2年": "1-3年",
                    "3年": "3-5年",
                    "4年": "3-5年",
                    "5-10年": "5-10年",
                    "5年": "5-10年",
                    "6年": "5-10年",
                    "7年": "5-10年",
                    "8年": "5-10年",
                    "9年": "5-10年",
                    "10年及以上": "10年以上",
                    不限: "不限",
                  }
                  const new_beisen_constant = {
                    ...beisen_constant,
                    Category: "1",
                    // todo枚举: 学历要求
                    Degree: "1",
                    DetailAddress: "",
                    Duty: job.content,
                    Email: "",
                    HeadCount: "0",
                    JobAdName: job.name,
                    JobCategoryCommon: "",
                    JobCode: "J10122",
                    // todo枚举: 工作性质
                    Kind: "1",
                    LocId: "3210",
                    MaxSalary: job.salaryMax,
                    MinSalary: job.salaryMin,
                    OrgId: "661322",
                    Require: job.askFor,
                    Salary: "",
                    SalaryType: "1",
                    YearsOfWorking: "1",
                    jobId: "150946774",
                  }

                  obj.adDetail = {
                    ...obj.adDetail,
                    job_ad_name: job.name,
                    duty: job.content,
                    require: job.askFor,
                    // 学历要求
                    degree_name: DEGREE_MAP[job.educationStr],
                    min_salary: job.salaryMin,
                    max_salary: job.salaryMax,
                    // head_count: job.recruitNum,
                    kind_name: obj.natureOfWorkStr,
                    year_of_working_description: EXP_MAP[job.experienceStr], //"5年",
                    // todo: test
                    beisen_constant: JSON.stringify(new_beisen_constant),
                  }

                  publishJobadFill(tabId, obj, channelJsData)
                } catch (error) {
                  console.log("publishJobadFill error: >>", error)
                }

                webRequestMap.clear()
                // 至此，建立源页面和目标页面之间的一对一关系
                webRequestMap.set(tabId, {
                  fromWindowId: sender.tab.windowId,
                  toWindowId: tabId,
                  payload: request,
                })
                console.log("🚀最新的webRequestMap: >>", webRequestMap)

                openWebRequestListener({ tabId })
                console.log("🚦openWebRequestListener tabId: >>", tabId)

                windowsFilledState.set(tabId, true)

                // chrome.tabs.sendMessage(tabId, {
                //   message: 'START_AUTO_FILL_RESUME',
                //   payload: request,
                // })
              }
            })
          }
        )
      }
    )
  }
}

function openWebRequestListener({ tabId }) {
  const cachedValue = webRequestMap.get(tabId)
  const payload = cachedValue.payload

  // 监听页面的请求
  chrome.webRequest.onCompleted.addListener(
    function (details) {
      if(!details.url.includes(payload.formConfig.callbackUrl)) return
      // 判断请求是否成功
      if (details.tabId === tabId && details.statusCode === 200) {

        if(windowsFilledState.get(tabId)){
          windowsFilledState.delete(tabId)
        }

        // HRMS_LOGIN_HOST "https://www.huamansoft.com/huamantest"
        getFromStorage('HRMS_LOGIN_HOST').then(loginHost => {
          let domain = 'https://www.huamansoft.com'
          const parsedUrl = new URL(loginHost)
          // 获取域名部分
          if(parsedUrl && parsedUrl.origin){
            domain = parsedUrl.origin
          }

          // 回调告知平台该广告已发送成功
          fetch(`${domain}/hrms/recruit/position/feedback`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(payload),
          })
            .then((res) => res.text())
            .then(() => {
              console.log("😍回调告知平台该广告已发送成功: >>", payload)
            })
            .catch((err) => console.log(err))

        })
      }
    },
    {
      // urls: ["https://proapi.azurewebsites.net/doc/*"],
      urls: [],
      // tabType: "popup",
      // types: ["main_frame", "sub_frame", "xmlhttprequest"],
      // tabId,
      // windowId: 12345,
    }
  )
}

// function getResponseBody(requestId) {
//   chrome.webRequest.onCompleted.addListener(
//     function(details) {
//       if (details.requestId === requestId) {
//         // 获取响应体
//         var responseHeaders = details.responseHeaders
//         var responseBody = ''

//         // 遍历响应头部，找到Content-Type
//         for (var i = 0; i < responseHeaders.length; i++) {
//           if (responseHeaders[i].name.toLowerCase() === 'content-type') {
//             var contentType = responseHeaders[i].value.toLowerCase()

//             // 判断Content-Type是否为文本类型
//             if (contentType.includes('text/plain') || contentType.includes('text/html') || contentType.includes('application/json')) {
//               // 获取响应体
//               responseBody = details.response
//               break
//             }
//           }
//         }

//         console.log("请求的响应体：", responseBody)
//         // 在这里处理响应体数据
//       }
//     },
//     { urls: ["<all_urls>"], types: ["xmlhttprequest", "fetch", "script"], tabId: -1 },
//     ["responseHeaders"]
//   )
// }
